﻿using DapperORM.Abstractions;
using DapperORM.Abstractions.Adapter;
using MySqlConnector;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;

namespace DapperORM.BulkMysql
{
    /// <summary>
    /// mysql
    /// </summary>
    public class MysqlBulk : IBulk
    {
        /// <summary>
        /// mysql的连接字符串里要添加";AllowLoadLocalInfile=true"，即连接字符串的形式应该是"Server= ;Database=;User ID=;Password=;AllowLoadLocalInfile=true"，
        /// 同时在mysql数据库上执行"set global local_infile=1"开启批量上传
        /// </summary>
        public async Task BulkInsetAsync<TEntity>(IDbConnection connection, IEnumerable<TEntity> entities, IDbTransaction transaction = null, int? commandTimeout = null) where TEntity : class
        {
            if (!(connection is MySqlConnection mySqlConnection))
                throw new Exception("connection is not MySqlConnection");
            if (mySqlConnection.State != ConnectionState.Open)
                await mySqlConnection.OpenAsync();
            var tran = transaction == null ? null : transaction as MySqlTransaction;
            var type = typeof(TEntity);
            var columns = SqlMapperEx.KeyPropertiesCache(type).Where(m => m.KeyType != KeyType.Identity).ToList();
            var mysqlBulkCopy = new MySqlBulkCopy(mySqlConnection, tran);
            mysqlBulkCopy.DestinationTableName = SqlMapperEx.GetTableName(type);
            if (commandTimeout.HasValue &&  commandTimeout.Value > 0)
                mysqlBulkCopy.BulkCopyTimeout = commandTimeout.Value;
            foreach (var item in columns)
            {
                mysqlBulkCopy.ColumnMappings.Add(new MySqlBulkCopyColumnMapping(columns.IndexOf(item), item.ColumnName));
             }

            var dataTable = entities.ToDataTable(columns);
            await mysqlBulkCopy.WriteToServerAsync(dataTable);
        }
    }
}
